<?php

namespace App\Http\Rest\Admin;

use Framework\Foundation\Database\FDB;
use Framework\Foundation\Response\ResponseGen;

class DbResource
{
    public function getList(array $restParams, $request)
    {
        $page = $request->getIn('pageNumber', 1);
        $pageSize = $request->getIn('pageSize', 10);
            
        $query = FDB::from($restParams['resource'])
            ->order($restParams['field']. ' desc ')
            ->where('is_deleted', 0);

        // 作一些其他参数where条件
        $total = $query->count();
        $query = $query->offset($pageSize * ($page - 1))->limit($pageSize);
        $ret = $query->fetchAll();

//        if (false == $ret) {
//            $errorMsg = $query->getMessage();
//            return ResponseGen::error(400, "请求Admin数据资源失败:" . $errorMsg);
//        }
        return ResponseGen::success(['total' => $total, 'rows' => $ret]);
    }

    public function getInfo(array $restParams, $request)
    {
        $query = FDB::from($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $info = $query->fetch();
        return ResponseGen::success($info);
    }

    public function add(array $restParams, $request)
    {
        $params = $request->getParsedBody();

        // 参数验证
        unset($params['files']);

        $query = FDB::insertInto($restParams['resource']);
        $ret = $query->values($params)->execute();
        if (!$ret) {
            return ResponseGen::error(400, "添加失败:".$query->getMessage());
        }
        return ResponseGen::success();
    }


    public function edit(array $restParams, $request)
    {
        // 参数验证
        $params = $request->getParsedBody();
        if (isset($params['_ajax_method'])) {
            unset($params['_ajax_method']);
        }

        $query = FDB::update($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $ret = $query->set($params)->execute();

        if (!$ret) {
            return ResponseGen::error(400, "列新失败:" . $query->getMessage());
        }
        return ResponseGen::success();
    }

    public function delete(array $restParams)
    {
        $query = FDB::update($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $ret = $query->set([
            'is_deleted' => 1,
            'deleted_at' => date('Y-m-d H:i:s')
        ])->execute();
        if (!$ret) {
            return ResponseGen::error(400, "删除失败");
        }
        return ResponseGen::success();
    }
}
